//
//  PKRadioPlayViewController.m
//  AMomentApp
//
//  Created by lanou on 15/10/6.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "PKRadioPlayViewController.h"
#import "UIImageView+WebCache.h"
#import "PKRequestManager.h"
#import "PKPlayerManager.h"
@interface PKRadioPlayViewController () <NSURLSessionDelegate,NSURLSessionDownloadDelegate>

@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *likeLabel;
@property (nonatomic, strong) UIButton *downButton;
@property (nonatomic, strong) UILabel *commentLabel;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UILabel *progressLabel;

@property (nonatomic, strong) NSData *data; // 用来存储未下载完成的数据
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSURLSessionDownloadTask *task;

@end

@implementation PKRadioPlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self showTheMusicPlayView];
    
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(progress) userInfo:nil repeats:YES];
    // Do any additional setup after loading the view.
}

- (void)showTheMusicPlayView
{
    _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(60, 60, SCREEN_WIDTH-120, SCREEN_WIDTH-120)];
    [_imageView sd_setImageWithURL:[NSURL URLWithString:_radioPlayModel.playInfo.imgUrl]];
    [self.view addSubview:_imageView];
    
    _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, SCREEN_WIDTH-40, SCREEN_WIDTH, 30)];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.text = _radioPlayModel.playInfo.title;
    [self.view addSubview:_titleLabel];
    
    UIImageView *likeImageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, SCREEN_WIDTH+10, 20, 20)];
    likeImageView.image = [UIImage imageNamed:@"heart"];
    [self.view addSubview:likeImageView];
    
    _likeLabel = [[UILabel alloc]initWithFrame:CGRectMake(130, SCREEN_WIDTH+10, 50, 20)];
    _likeLabel.font = [UIFont systemFontOfSize:14];
    _likeLabel.text = [NSString stringWithFormat:@"%@",_radioPlayModel.like];
    [self.view addSubview:_likeLabel];
    
    UIImageView *commentImageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-150, SCREEN_WIDTH+10, 20, 20)];
    commentImageView.image = [UIImage imageNamed:@"comments"];
    [self.view addSubview:commentImageView];
    
    _commentLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-120, SCREEN_WIDTH+10, 60, 20)];
    _commentLabel.font = [UIFont systemFontOfSize:14];
    _commentLabel.text = [NSString stringWithFormat:@"%@",_radioPlayModel.comment];
    [self.view addSubview:_commentLabel];

//    _downButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    _downButton.frame = CGRectMake(70, SCREEN_WIDTH+50, 20, 20);
//    [_downButton setImage:[UIImage imageNamed:@"download"] forState:UIControlStateNormal];
//    [_downButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateSelected];
//    [_downButton addTarget:self action:@selector(downloadTheMP3:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:_downButton];
    
    _progressLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, SCREEN_WIDTH+70, 60, 20)];
    [self.view addSubview:_progressLabel];
    
    _progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(100, SCREEN_WIDTH+60, SCREEN_WIDTH/2-30, 30)];
    _progressView.progressViewStyle = UIProgressViewStyleDefault;
    _progressView.progressTintColor = [UIColor blackColor];
    [self.view addSubview:_progressView];
    
    _timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2+90, SCREEN_WIDTH+50, 80, 30)];
    [self.view addSubview:_timeLabel];
}

// 更新数据
- (void)UPdateData:(PKPlayModel *)Model
{
    [_imageView sd_setImageWithURL:[NSURL URLWithString:Model.playInfo.imgUrl]];
    _titleLabel.text = Model.playInfo.title;
    _likeLabel.text = [NSString stringWithFormat:@"%@",Model.like];
    _commentLabel.text = [NSString stringWithFormat:@"%@",Model.comment];
}

- (void)progress
{
    PKPlayerManager *playManager = [PKPlayerManager sharedManager];
    
    self.progressView.progress = (CGFloat)playManager.currentTime / playManager.finishTime;
    NSUInteger time = playManager.finishTime - playManager.currentTime;
    NSUInteger minutes = time / 60;
    NSUInteger seconds = time % 60;
    
    _timeLabel.text = [NSString stringWithFormat:@"%0.2lu:%0.2lu",(unsigned long)minutes,(unsigned long)seconds];
}

// 开始下载 暂停/继续下载
- (void)downloadTheMP3:(UIButton *)button
{
    _downButton.selected = !_downButton.selected;
    if (_downButton.selected == NO) {
        // 执行这个方法会取消task(下载任务)正在下载的内容，同时会返回一个resumeData，这个resumeData就是取消之前已经下载的那部分数据，可以存为属性，用于断点下载，
        [self.task cancelByProducingResumeData:^(NSData *resumeData) {
            // 用self.data来保存下载的不完整的resumeData
            self.data = resumeData;
        }];
    }else
    {
        // 判断有不完整的data就接着之前的下载，没有就从头开始下载
        if (self.data) {
             // 让task(下载任务)继续下载 执行这个方法要传给_session一个不完整的data， 让继续之前的下载。这个data不可以为空
            self.task = [_session downloadTaskWithResumeData:self.data];
            // 让这个task(下载任务)开始下载
            [self.task resume];
        }else
        {
            // 从头开始下载
            [self beginRequest];
        }
    }
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    // location是已经下载完成的文件的位置
    // 通过这种方式下载的文件会被保存到一个临时文件夹里，我需要用的话应该放到我们自己的文件夹里,下载好的文件都是tmp后缀的文件
    NSLog(@"location:%@",location);
    // 创建一个文件
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // 使用传过来的位置来获取最后一个信息，就是文件的名字CFNetworkDownload_vXMZfE.tmp
    NSString *fileName = [location lastPathComponent];
    //tmp文件不能播放 可以换一个后缀
    NSString *newFileName = [fileName stringByReplacingOccurrencesOfString:@"tmp" withString:@"mp3"];
    // 获取Document路径
    NSURL *documentURL = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    // 拼接新文件的储存路径
    NSURL *newFilePath = [documentURL URLByAppendingPathComponent:newFileName];
    // 使用文件管理类，把临时文件夹里的文件拷贝到新创建的Document目录下
    [fileManager copyItemAtURL:location toURL:newFilePath error:nil];
    // 使用文件管理类手动移除临时文件夹的文件
    [fileManager removeItemAtURL:location error:nil];
    
    [_downButton setImage:[UIImage imageNamed:@"download"] forState:UIControlStateNormal];
    NSLog(@"%@", newFilePath);
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    _progressLabel.text = [NSString stringWithFormat:@"%0.2f%%",(double)totalBytesWritten / totalBytesExpectedToWrite * 100];
}

// 开始下载
- (void)beginRequest 
{
    // 创建NSURLSessionConfiguration用于后面创建NSURLSession
    NSURLSessionConfiguration *sessionConfigure = [NSURLSessionConfiguration defaultSessionConfiguration];
   // 根据之前创建的NSURLSessionConfiguration创建一个NSURLSession ,同时设置代理对象为自己，来实现下载完成、下载进度的方法
    _session = [NSURLSession sessionWithConfiguration:sessionConfigure delegate:self delegateQueue:[NSOperationQueue currentQueue]];
    // 给_session设置下载的内容，设置完成后会返回一个NSURLSessionDownloadTask，这个task 可以理解为是我们这个下载任务，我们可以通过这个task来管理这个下载任务，比如 暂停 继续 开始 等。
    self.task = [_session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.mArray[_row]]]];
    // 让这个task(下载任务)开始下载
    [self.task resume];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
